var dispatcher = require("../../../util/dispatcher");

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next stemp callback
 *
 */
Handler.prototype.queryEntry = function (msg, session, next) {
    console.log("有玩家登录游戏");
    // console.log(msg);
    // console.log(session);
    var uid = msg.uid;
    if (!uid) {
        next(null, {
            code: 500,
            msg: "登录信息中必须携带玩家【uid】"
        });
        return;
    }
    // get all connectors
    var connectors = this.app.getServersByType("connector");
    if (!connectors || connectors.length === 0) {
        next(null, {
            code: 500 // 服务器错误。
        });
        return;
    }

    // console.log(connectors);
    // select connector
    var res = dispatcher.dispatch(uid, connectors);
    // console.log("查询connector的结果");
    // console.log(res);
    next(null, {
        code: 200, // 表明该请求被成功地完成，所请求的资源发送到客户端。
        host: res["host"], // 主机地址
        port: res["clientPort"] // 客户端连接的端口号
    });
};